package com.jwdf.uda.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Toast;

import com.jwdf.uda.R;
import com.jwdf.uda.app.AppContext;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.bean.UploadImageResponse;
import com.jwdf.uda.event.QuizDetailEvent;
import com.jwdf.uda.http.AHttpService;
import com.jwdf.uda.http.HttpHelper;
import com.jwdf.uda.http.action.AnswerEditAction;
import com.jwdf.uda.http.action.UploadImageAction;
import com.jwdf.uda.ui.fragment.question.bean.EditDescribe;
import com.jwdf.uda.ui.fragment.question.bean.NewAnswer;
import com.jwdf.uda.utils.AppBus;
import com.jwdf.uda.utils.ConfigUtils;
import com.jwdf.uda.utils.DisplayUtils;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.view.imagegetter.UiImageGetter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import retrofit2.Response;

public class EditAnswerActivity extends AnswerActivity {

    private static String strAnswer = "answer";
    private NewAnswer answer;
    public static void start(Context context, PbBean.PbResQuestionFindAnswer answer, int voteCount) {
        Intent intent = new Intent(context, EditAnswerActivity.class);
        NewAnswer par = onParsingData(answer);
        intent.putExtra(strAnswer, par);
        intent.putExtra(strVoteCount, voteCount);
        context.startActivity(intent);
    }

    private static NewAnswer onParsingData(PbBean.PbResQuestionFindAnswer bean) {

        final NewAnswer instance = NewAnswer.getInstance();
        instance.setVote(bean.getVoteOption());

        PbBean.PbBaseQuestionAnswer answer = bean.getAnswerInfo();
        final List<PbBean.PbBaseResDescription> descInfoList = answer.getDescInfoList();
        instance.setmDescribe(onDescribe(descInfoList));
        instance.setEditDescribeList(onEditDescribeList(descInfoList));
        instance.setId(answer.getAnswerId());
        instance.setTitle(bean.getQuestionTitle());
        instance.setImageList(onImageList(descInfoList));
        instance.setURLToken(onMapURLToken(descInfoList));

        return instance;
    }

    private static String onDescribe(List<PbBean.PbBaseResDescription> description) {
        String descriptions = "";
        for(int i = 0; i < description.size(); i++) {
            if(description.get(i).getDescType() == PbBean.PbSignBaseDescriptionType.DESCRIPTION_TPYE_TEXT) {
                descriptions = descriptions + description.get(i).getDescText();
            } else {
                String tagPath = "<img src=\"" + description.get(i).getDescImage().getUrl() + "\"/>";
                descriptions = descriptions + tagPath;
            }
        }
        return descriptions;
    }

    private static List<EditDescribe> onEditDescribeList(List<PbBean.PbBaseResDescription> description) {
        List<EditDescribe> list = new ArrayList<>();
        for(int i = 0; i < description.size(); i++) {
            EditDescribe editDescribe = new EditDescribe();
            if(description.get(i).getDescType() == PbBean.PbSignBaseDescriptionType.DESCRIPTION_TPYE_TEXT) {
                editDescribe.setDescribe(0);
                editDescribe.setmName(description.get(i).getDescText());
                list.add(editDescribe);
            } else {
                editDescribe.setDescribe(1);
                editDescribe.setmUrl(description.get(i).getDescImage().getUrl());
                editDescribe.setToken(description.get(i).getDescImage().getToken());
                list.add(editDescribe);
            }
        }
        return list;
    }

    private static List<String> onImageList(List<PbBean.PbBaseResDescription> description) {
        List<String> list = new ArrayList<>();
        for(int i = 0; i < description.size(); i++) {
            if(description.get(i).getDescType() == PbBean.PbSignBaseDescriptionType.DESCRIPTION_TPYE_IMG) {
                list.add(description.get(i).getDescImage().getUrl());
            }
        }
        return list;
    }

    private static Map<String, String> onMapURLToken(List<PbBean.PbBaseResDescription> description) {
        Map<String, String> map = new HashMap<>();
        for(int i = 0; i < description.size(); i++) {
            if(description.get(i).getDescType() == PbBean.PbSignBaseDescriptionType.DESCRIPTION_TPYE_IMG) {
                map.put(description.get(i).getDescImage().getUrl(), description.get(i).getDescImage().getToken());
            }
        }
        return map;
    }

    protected void initViews() {
        checkPermission();

        instance = NewAnswer.getInstance();

        // FIXME: 2016/9/23 something usage
        mBinding = DataBindingUtil.setContentView(this, R.layout.lay_new_answer);

        vVoteNone = new View(this);
        vVoteNone.setTag(PbBean.PbSignBaseVoteOptionType.VOTE_OPTION_TYPE_NONE);
        vSel = vVoteNone;


        /** DisplayMetrics获取屏幕信息 */
        final DisplayMetrics displayMetrics = getResources().getDisplayMetrics();

        ViewTreeObserver vto = mBinding.et.getViewTreeObserver();
        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            public boolean onPreDraw() {
                screeWidth = mBinding.et.getMeasuredWidth();
                return true;
            }
        });
        screeHeight = displayMetrics.heightPixels;

        mBinding.et.getLayoutParams().height = DisplayUtils.getDeviceHeight(this) / 7 * 4;

        //getCategoryGet();
        mBinding.et.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                //触摸的是EditText并且当前EditText可以滚动则将事件交给EditText处理；否则将事件交由其父类处理
                if((view.getId() == R.id.et && canVerticalScroll(mBinding.et))) {
                    mBinding.et.clearFocus();
                    //mBinding.editDescribe.setFocusable(false);
                    view.getParent().requestDisallowInterceptTouchEvent(true);
                    if(event.getAction() == MotionEvent.ACTION_UP) {
                        view.getParent().requestDisallowInterceptTouchEvent(false);
                        //mBinding.editDescribe.findFocus();
                        //mBinding.editDescribe.setFocusable(true);
                    }
                }
                return false;
            }
        });

        initAnswer();

        findViewById(R.id.vBack).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        findViewById(R.id.tvHeadOperate).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showProgressDialog();
                doUploadAImagesAction();
            }
        });
    }

    private void initAnswer() {
        answer = getIntent().getParcelableExtra(strAnswer);
        if(!answer.getmDescribe().equals(""))
            getDraftBox(answer.getEditDescribeList());
        initVote(getIntent().getIntExtra(strVoteCount, 0));
        performClickVote(answer.getVote());

    }
    private void getDraftBox(List<EditDescribe> editDescribeList) {
        List<EditDescribe> list = editDescribeList;
        Editable eb = mBinding.et.getEditableText();
        int startPosition;

        for(int i = 0; i < list.size(); i++) {
            if(list.get(i).getDescribe() == 1) {
                startPosition = mBinding.et.getSelectionStart();
                UiImageGetter imageGetter = new UiImageGetter(mBinding.et, this, AppContext.getInstance(), screeWidth);
                eb.insert(startPosition, Html.fromHtml("<img src=" + list.get(i).getmUrl() + ">", imageGetter, null));
            } else {
                startPosition = mBinding.et.getSelectionStart();
                eb.insert(startPosition, list.get(i).getmName());
            }
        }

        mBinding.et.invalidate();
    }
    private void doUploadAImagesAction() {
        SaveDescribes(mBinding.et.getText().toString(), saveImage());

        if(Commitable()) {
            getDraftBoxs(mBinding.et.getText().toString(), saveImage());
            List<EditDescribe> list2 = instance.getEditDescribeList();
            boolean hasImageAToken = doUploadImagesAction();
            if(hasImageAToken) {
                doHasImageTokenSuccess(list2);
            }
        } else {
            if(isContentLess())
                toastContentLess();
            else if(isContentMuch())
                toastContentMuch();

            new Handler().post(new Runnable() {
                public void run() {
//                    TaskList taskList = new TaskList();
//                    taskList.setType("编辑答案");
//                    taskList.setName(answer.getTitle());
//                    taskList.setmTaskType(UPLOAD_EDIT);
//                    LongTask.getInstance().setListList(taskList);
//                    EventBusUtil.post(new LongTaskEvent(LongTaskEvent.LONG_TASK_QUESTION_SHOW, taskList));
//                    //        NewProblems.getInstance().setContext(getContext());
//                    setIsRequest(false);
                    // do something
                    getDraftBoxs(mBinding.et.getText().toString(), saveImage());
                    doUploadImagesAction();
                }

            });
        }
    }
    public void getDraftBoxs(String describe, List<String> imageList) {
        NewAnswer.getInstance().deleteEditDescribeList();
        String content = describe;
        String[] mContent = content.split("￼");

        int i = 0;
        /**
         * 获得草稿的图片和文字信息，并把它展示出来
         */
        for(String string : mContent) {
            //LogUtils.d(string);
            EditDescribe editDescribe = new EditDescribe();
            if(!TextUtils.isEmpty(string)) {
                editDescribe.setDescribe(0);
                editDescribe.setmName(string);
                NewAnswer.getInstance().setEditDescribeList(editDescribe);
            }
            if(i != mContent.length - 1) {
                String mPicPath = imageList.get(i);
                editDescribe = new EditDescribe();
                if(isURL(mPicPath)) {
                    editDescribe.setDescribe(1);
                    editDescribe.setURL(false);
                    editDescribe.setmUrl(mPicPath);
                    editDescribe.setToken(NewAnswer.getInstance().getURLToken(mPicPath));
                    NewAnswer.getInstance().setEditDescribeList(editDescribe);
                } else {
                    editDescribe.setURL(true);
                    editDescribe.setDescribe(1);
                    editDescribe.setmUrl(mPicPath);
                    NewAnswer.getInstance().setEditDescribeList(editDescribe);
                }
                i++;
            }
        }
    }
    private boolean doUploadImagesAction() {
        List<EditDescribe> list2 = instance.getEditDescribeList();
        for(int i = 0; i < list2.size(); i++) {
            if(list2.get(i).getDescribe() == 1 && list2.get(i).isURL()) {
                doUploadImageAction(i, "file://" + list2.get(i).getmUrl());
            }
        }
        return true;
    }

    private void doUploadImageAction(final int plan, final String imageUrl) {
        UploadImageAction action = new UploadImageAction(AppContext.getInstance(), imageUrl);
        onNewRequestCall(action.request(new UploadImageAction.IResCallback<String>() {
            @Override
            public void onCallback(int resultCode, UploadImageResponse response) {
                if(HttpHelper.showError(EditAnswerActivity.this, resultCode, response, getString(R.string.error_operation))) {
                    return;
                }
                doUploadImageResponse(plan, imageUrl, response);
            }
        }));


    }

    private void doUploadImageResponse(int plan, String imageUrl, UploadImageResponse response) {
        instance.getEditDescribeList().get(plan).setToken(response.getToken());
        List<EditDescribe> list2 = instance.getEditDescribeList();

        doHasImageTokenSuccess(list2);
    }

//    private void getDraftBox(String describe, List<String> imageList) {
//        instance.deleteEditDescribeList();
//        String content = describe;
//        String[] mContent = content.split("\n");
//
//        int i = 0;
//        /**
//         * 获得草稿的图片和文字信息，并把它展示出来
//         */
//        for(String string : mContent) {
//            //LogUtils.d(string);
//            EditDescribe editDescribe = new EditDescribe();
//            if(string.contains("￼")) {
//                /**
//                 * 如果是图片
//                 * 1,先判断其来自与照相机还是图库
//                 * 2，图库用ImageGetter显示出来
//                 * 3，照片用ImageGetter1显示出来
//                 */
//
//                String mPicPath = imageList.get(i);
//                if(mPicPath.contains("content")) {
//                    if(isURL(mPicPath)) {
//                        editDescribe.setDescribe(1);
//                        editDescribe.setURL(false);
//                        editDescribe.setmUrl(mPicPath);
//                        editDescribe.setToken(instance.getURLToken(mPicPath));
//                    } else {
//                        editDescribe.setURL(true);
//                        editDescribe.setDescribe(1);
//                        editDescribe.setmUrl(mPicPath);
//                    }
//
//                } else {
//                    if(isURL(mPicPath)) {
//                        editDescribe.setDescribe(1);
//                        editDescribe.setURL(false);
//                        editDescribe.setmUrl(mPicPath);
//                        editDescribe.setToken(instance.getURLToken(mPicPath));
//                    } else {
//                        editDescribe.setURL(true);
//                        editDescribe.setDescribe(1);
//                        editDescribe.setmUrl(mPicPath);
//                    }
//                }
//                i++;
//                /**
//                 * 碰到图片下面直接有文字的情况
//                 */
//                if(!string.equals("￼")) {
//                    instance.setEditDescribeList(editDescribe);
//                    editDescribe = new EditDescribe();
//                    String contentPic = string.substring(string.indexOf("￼") + 1);
//                    editDescribe.setDescribe(0);
//                    editDescribe.setmName(contentPic);
//                }
//            } else {
//                /**
//                 * 展示文字
//                 */
//                editDescribe.setDescribe(0);
//                editDescribe.setmName(string);
//            }
//            NewAnswer.getInstance().setEditDescribeList(editDescribe);
//        }
//    }

//    private void getDraftBoxs(String describe, List<String> imageList) {
//        NewAnswer.getInstance().deleteEditDescribeList();
//        String content = describe;
//        Editable eb = mBinding.et.getEditableText();
//        String[] mContent = content.split("￼");
//
//        int startPosition;
//        int i = 0;
//        /**
//         *
//         * 获得草稿的图片和文字信息，并把它展示出来
//         */
//        for(String string : mContent) {
//            //LogUtils.d(string);
//            EditDescribe editDescribe = new EditDescribe();
//            if(!TextUtils.isEmpty(string)) {
//                startPosition = mBinding.et.getSelectionStart();
//                eb.insert(startPosition, string);
//                editDescribe.setDescribe(0);
//                editDescribe.setmName(string);
//                NewAnswer.getInstance().setEditDescribeList(editDescribe);
//            }
//            if(i != mContent.length - 1) {
//                String mPicPath = imageList.get(i);
//                startPosition = mBinding.et.getSelectionStart();
//                eb.insert(startPosition, Html.fromHtml("<img src=" + mPicPath + ">", imageGetter, null));
//                editDescribe = new EditDescribe();
//                editDescribe.setDescribe(1);
//                editDescribe.setmUrl(mPicPath);
//                NewAnswer.getInstance().setEditDescribeList(editDescribe);
//                i++;
//            }
//        }
//    }

    private boolean isURL(String url) {
        String str = "http";
        return url.contains(str);
    }

    protected void onPublished() {
        if(mBinding.et.getText().length() > 0) {
            List<PbBean.PbBaseReqDescription> descriptionList = getDescriptionList();
            final PbBean.PbSignBaseVoteOptionType vote = (PbBean.PbSignBaseVoteOptionType) vSel.getTag();

            AnswerEditAction action = new AnswerEditAction(this, answer.getId(), vote, descriptionList);
            onNewRequestCall(action.request(new AHttpService.IResCallback<PbBean.PbResQuestionEditAnswer>() {
                @Override
                public void onCallback(int resultCode, Response<PbBean.PbResQuestionEditAnswer> response, PbBean.PbBaseServerInfo baseServerInfo) {
                    closeProgressDialog();
                    if(HttpHelper.showError(EditAnswerActivity.this, resultCode, baseServerInfo, getString(R.string.error_net))) {
                        return;
                    }
                    Toast.makeText(EditAnswerActivity.this, "发表成功", Toast.LENGTH_LONG).show();

                    instance.delete();
                    ConfigUtils.removeNewAnswer(EditAnswerActivity.this);
                    finish();

                    AppBus.getInstance().post(ReplyDetaiActivtiy.ReplyDetailFragment.strEditAnswer);
                    EventBusUtil.post(new QuizDetailEvent(QuizDetailEvent.EVENT_QUIZ_REPLY_EDIT));
                }
            }));
        } else {
            closeProgressDialog();
            Toast.makeText(this, "描述不能为空", Toast.LENGTH_LONG).show();
        }
    }
    @Override
    public void onBackPressed() {

        FragmentManager manager = getSupportFragmentManager();
        int count = manager.getBackStackEntryCount();
        if(count == 0) {
            instance.delete();
            finish();
        }

    }
}
